import { useState } from 'react';

export interface OcrResult {
  text: string;
  confidence: number[];
  averageConfidence: number;
  wordCount: number;
  rawResult: any;
  timestamp: string;
}

export interface OcrError {
  message: string;
  details?: string;
  statusCode?: number;
}

export function useOcr() {
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<OcrError | null>(null);
  const [lastResult, setLastResult] = useState<OcrResult | null>(null);

  const recognizeText = async (imageFile: File): Promise<OcrResult> => {
    setIsProcessing(true);
    setError(null);

    try {
      // 检查文件类型
      if (!imageFile.type.startsWith('image/')) {
        throw new Error('只支持图片文件');
      }

      // 检查文件大小（10MB限制）
      if (imageFile.size > 10 * 1024 * 1024) {
        throw new Error('图片文件过大，请上传10MB以下的图片');
      }

      console.log('开始OCR识别:', imageFile.name, '大小:', imageFile.size);

      const formData = new FormData();
      formData.append('image', imageFile);

      // 获取API基础URL
      const apiBase = window.__API_BASE__ || 'http://localhost:8001';
      const response = await fetch(`${apiBase}/api/ocr/recognize`, {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `HTTP错误: ${response.status}`);
      }

      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '识别失败');
      }

      const ocrResult = result.data;
      setLastResult(ocrResult);
      
      console.log('OCR识别成功:', ocrResult);
      return ocrResult;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '识别失败';
      const ocrError: OcrError = {
        message: errorMessage,
        details: err instanceof Error ? err.stack : undefined
      };
      
      setError(ocrError);
      console.error('OCR识别失败:', err);
      throw err;
    } finally {
      setIsProcessing(false);
    }
  };

  const recognizeMultipleImages = async (imageFiles: File[]): Promise<{
    results: Array<{ index: number; success: boolean; data?: OcrResult; error?: string }>;
    totalCount: number;
    successCount: number;
    errorCount: number;
  }> => {
    setIsProcessing(true);
    setError(null);

    try {
      // 检查文件数量
      if (imageFiles.length === 0) {
        throw new Error('请选择图片文件');
      }

      if (imageFiles.length > 5) {
        throw new Error('最多支持5张图片同时识别');
      }

      // 检查文件类型和大小
      for (const file of imageFiles) {
        if (!file.type.startsWith('image/')) {
          throw new Error(`文件 ${file.name} 不是图片格式`);
        }
        if (file.size > 10 * 1024 * 1024) {
          throw new Error(`图片 ${file.name} 过大，请上传10MB以下的图片`);
        }
      }

      console.log('开始批量OCR识别:', imageFiles.length, '张图片');

      const formData = new FormData();
      imageFiles.forEach((file, index) => {
        formData.append('images', file);
      });

      // 获取API基础URL
      const apiBase = window.__API_BASE__ || 'http://localhost:8001';
      const response = await fetch(`${apiBase}/api/ocr/recognize-batch`, {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || `HTTP错误: ${response.status}`);
      }

      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '批量识别失败');
      }

      console.log('批量OCR识别成功:', result.data);
      return result.data;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '批量识别失败';
      const ocrError: OcrError = {
        message: errorMessage,
        details: err instanceof Error ? err.stack : undefined
      };
      
      setError(ocrError);
      console.error('批量OCR识别失败:', err);
      throw err;
    } finally {
      setIsProcessing(false);
    }
  };

  const clearError = () => {
    setError(null);
  };

  const clearResult = () => {
    setLastResult(null);
  };

  const reset = () => {
    setIsProcessing(false);
    setError(null);
    setLastResult(null);
  };

  return {
    recognizeText,
    recognizeMultipleImages,
    isProcessing,
    error,
    lastResult,
    clearError,
    clearResult,
    reset
  };
}
